<template>
  <a-spin :spinning="loading">
    <div class="modal-header">
      <div class="modal-title">
        {{ l('Personalized.ListConfiguration') }}
      </div>
    </div>
    <slot></slot>
    <div class="modal-body">
      <a-table
        :columns="columns"
        :data-source="dataSourceSort"
        bordered
        style="padding: 8px"
        size="small"
        :rowKey="(record) => record.field"
        :pagination="false"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex == 'title'"> {{ l(record.title) }} </template>
          <template v-if="column.dataIndex == 'sortNum'">
            <arrow-up-outlined
              v-if="record.sortNum > 0"
              style="cursor: pointer; padding: 0 4px"
              @click="handleSortNum('up', record)"
            />
            <a-divider
              type="vertical"
              v-if="record.sortNum > 0 && record.sortNum < dataSource.length - 1"
            />
            <arrow-down-outlined
              v-if="record.sortNum < dataSource.length - 1"
              style="cursor: pointer; padding: 0 4px"
              @click="handleSortNum('down', record)"
            />
          </template>
          <template
            v-if="['width', 'position', 'ifShow', 'type', 'fixed'].includes(column.dataIndex)"
          >
            <div>
              <a-input-number
                v-if="column.dataIndex == 'width' && editableData[record?.field ?? record.type]"
                v-model:value="editableData[record?.field ?? record.type][column.dataIndex]"
                :min="0"
                :max="999"
              />
              <a-select
                v-else-if="
                  column.dataIndex == 'fixed' && editableData[record?.field ?? record.type]
                "
                v-model:value="editableData[record?.field ?? record.type][column.dataIndex]"
                style="width: 100%"
                allowClear
              >
                <a-select-option value="left">{{ l('Personalized.LeftFixed') }}</a-select-option>
                <a-select-option value="right">{{ l('Personalized.RightFixed') }}</a-select-option>
              </a-select>
              <a-select
                v-else-if="
                  column.dataIndex == 'position' && editableData[record?.field ?? record.type]
                "
                v-model:value="editableData[record?.field ?? record.type][column.dataIndex]"
                style="width: 100%"
              >
                <a-select-option value="left">{{ l('Personalized.LeftAlign') }}</a-select-option>
                <a-select-option value="center">{{
                  l('Personalized.CenterAlign')
                }}</a-select-option>
                <a-select-option value="right">{{ l('Personalized.RightAlign') }}</a-select-option>
              </a-select>
              <a-switch
                v-else-if="
                  column.dataIndex == 'ifShow' && editableData[record?.field ?? record.type]
                "
                v-model:checked="editableData[record?.field ?? record.type][column.dataIndex]"
                :min="0"
              />
              <a-input
                v-else-if="editableData[record?.field ?? record.type]"
                v-model:value="editableData[record?.field ?? record.type][column.dataIndex]"
                allowClear
              />
              <template v-else>
                <template v-if="column.dataIndex == 'ifShow'">
                  <CheckCircleTwoTone v-if="record.ifShow" twoToneColor="#52c41a" />
                  <CloseCircleTwoTone v-else twoToneColor="#ff0000" />
                </template>
                <template v-else-if="column.dataIndex == 'fixed'">
                  <span v-if="record.fixed == 'left'">{{ l('Personalized.LeftFixed') }}</span>
                  <span v-else-if="record.fixed == 'right'">{{
                    l('Personalized.RightFixed')
                  }}</span>
                </template>
                <template v-else-if="column.dataIndex == 'position'">
                  <align-left-outlined v-if="record.position == 'left'" />
                  <align-center-outlined v-else-if="record.position == 'center'" />
                  <align-right-outlined v-else-if="record.position == 'right'" />
                </template>

                <span v-else>{{ text }}</span>
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record?.field ?? record.type]">
                <a @click="save(record?.field ?? record.type)">{{ l('Save') }}</a>
                <a-divider type="vertical" />
                <a @click="cancel(record?.field ?? record.type)">{{ l('Cancel') }}</a>
              </span>
              <span v-else>
                <a @click="edit(record?.field ?? record.type)">{{ l('Edit') }}</a>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <div class="modal-footer">
      <a-button :disabled="saving" @click="close()" type="button">
        <close-circle-outlined />
        {{ l('Cancel') }}
      </a-button>
      <a-button :disabled="saving" @click="handleResetClick()" type="button">
        <close-circle-outlined />
        {{ l('Reset') }}
      </a-button>
      <a-button :loading="saving" :type="'primary'" @click="handleSave()">
        <save-outlined />
        {{ l('Save') }}
      </a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { cloneDeep } from 'lodash-es';
  import { defineComponent } from 'vue';
  import {
    ListViewsServiceProxy,
    SaveListViewAsPersonalInput,
    ListViewDto,
    ListViewColumnsDto,
  } from '/@/shared/service-proxies';
  import { ModalComponentBase } from '/@/shared/component-base';
  import {
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    ArrowUpOutlined,
    ArrowDownOutlined,
    AlignLeftOutlined,
    AlignCenterOutlined,
    AlignRightOutlined,
  } from '@ant-design/icons-vue';
  export default defineComponent({
    name: 'ListConfigModal',
    mixins: [ModalComponentBase],
    props: {
      json: {
        type: Object,
        required: true,
        default: {},
      },
    },
    components: {
      CheckCircleTwoTone,
      CloseCircleTwoTone,
      ArrowUpOutlined,
      ArrowDownOutlined,
      AlignLeftOutlined,
      AlignCenterOutlined,
      AlignRightOutlined,
    },
    data() {
      return {
        listViewsServiceProxy: new ListViewsServiceProxy(this.$apiUrl, this.$api),
        columns: [
          {
            title: this.l('Sort'),
            dataIndex: 'sortNum',
            width: 120,
            align: 'center',
          },
          {
            title: this.l('Personalized.Attribute'),
            dataIndex: 'title',
            width: 200,
          },
          {
            title: this.l('Width'),
            dataIndex: 'width',
            width: 120,
          },
          {
            title: this.l('Personalized.Freeze'),
            dataIndex: 'fixed',
            width: 120,
          },
          {
            title: this.l('Personalized.Alignment'),
            dataIndex: 'position',
            width: 120,
            align: 'center',
          },
          {
            title: this.l('IsShow'),
            dataIndex: 'ifShow',
            width: 120,
            align: 'center',
          },
          {
            title: this.l('Action'),
            dataIndex: 'operation',
            width: 120,
          },
        ],
        dataSource: cloneDeep(this.json?.listViewColumns ?? []),
        editableData: {} as any,
      };
    },
    watch: {
      json(val) {
        this.dataSource = cloneDeep(val?.listViewColumns ?? []);
      },
    },
    computed: {
      dataSourceSort() {
        return this.dataSource.sort((a: ListViewColumnsDto, b: ListViewColumnsDto) => {
          return (a?.sortNum ?? 0) - (b?.sortNum ?? 0);
        });
      },
    },
    methods: {
      /**
       * 重置
       */
      handleResetClick() {
        abp.message.confirm(null, this.l('MessageConfirmOperation'), (isConfirmed: boolean) => {
          if (isConfirmed) {
            this.loading = true;
            this.listViewsServiceProxy
              .deletePersonalListView(this.json.listViewName)
              .then((res) => {
                abp.notify.success(this.l('SavedSuccessfully'));
                this.handleClose();
                this.success();
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      handleSave() {
        const params = new SaveListViewAsPersonalInput({
          userId: this.abpSession?.userId ?? -1,
          listViewDto: cloneDeep(this.json) as ListViewDto,
        });
        params.listViewDto.listViewColumns = this.dataSourceSort;
        this.loading = true;
        this.listViewsServiceProxy
          .saveListViewAsPersonal(params)
          .then(() => {
            abp.notify.success(this.l('SavedSuccessfully'));
            this.handleClose();
            this.success(true);
          })
          .finally(() => {
            this.loading = false;
          });
      },
      handleClose() {
        this.editableData = {};
      },

      /****************************** */
      /**
       * 编辑
       */
      edit(key: string) {
        this.editableData[key] = cloneDeep(
          this.dataSourceSort.filter(
            (item: ListViewColumnsDto) => key === (item?.field ?? item.type),
          )[0],
        );
      },
      /**
       * 保存
       */
      save(key: string) {
        Object.assign(
          this.dataSourceSort.filter(
            (item: ListViewColumnsDto) => key === (item?.field ?? item.type),
          )[0],
          this.editableData[key],
        );
        delete this.editableData[key];
      },
      /**
       * 取消
       */
      cancel(key: string) {
        delete this.editableData[key];
      },
      /**
       * 改变排序
       */
      handleSortNum(type: string, record: any) {
        const { sortNum } = record;
        if (type == 'up') {
          this.dataSource.map((item: ListViewColumnsDto) => {
            if (sortNum - 1 == item.sortNum) {
              item.sortNum = item.sortNum + 1;
            } else if (sortNum == item.sortNum) {
              item.sortNum = (item?.sortNum ?? 0) - 1;
            }

            return item;
          });
        } else {
          this.dataSource.map((item: ListViewColumnsDto) => {
            if (sortNum + 1 == item.sortNum) {
              item.sortNum = (item?.sortNum ?? 0) - 1;
            } else if (sortNum == item.sortNum) {
              item.sortNum = (item?.sortNum ?? 0) + 1;
            }
            return item;
          });
        }
      },
    },
  });
</script>

<style scoped></style>
